﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Reflection;

using Bandit.Helpers;

namespace IOT.DongleFlashTool
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        System.Threading.Mutex _Mutex;

        public App()
        {
            this.DispatcherUnhandledException += (sender, e) =>
            {
                LogHelper.Error(e.Exception, "DispatcherUnhandledException");

                e.Handled = true;

                if (Bandit.UI.BanditDialog.Show(e.Exception.GetMessage() + Environment.NewLine + "呃...发生意外错误，是否继续运行程序？", "通告", MessageBoxButton.YesNo, Bandit.UI.DialogIcon.Shame) == MessageBoxResult.No)
                {
                    this.Shutdown();
                }
            };

            // 退出程序，记录log
            this.Exit += delegate
            {
                LogHelper.Info("关闭程序！");
            };

            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                Exception ex = e.ExceptionObject as Exception;

                LogHelper.Error(ex, "UnhandledException");

                Dispatcher.Invoke((Action)delegate
                {
                    Bandit.UI.BanditDialog.Show(ex.GetMessage() + Environment.NewLine + "呃...不明力量入侵，程序崩溃了！！！", "通告", MessageBoxButton.OK, Bandit.UI.DialogIcon.Shame);
                });
            };

            this.Startup += delegate
            {
                bool ret;
                string name = Assembly.GetExecutingAssembly().FullName.Split(new char[] { ',' })[0];
                _Mutex = new System.Threading.Mutex(true, name, out ret);
                if (!ret)
                {
                    Environment.Exit(0);
                }
            };
        }
    }
}
